//
//  MapConfig.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/11.
//

import Foundation
import MapKit

class MapConfig: ObservableObject {
   static let shared = MapConfig()

   private init() {
      print("------------------ MapConfig inited -----------------")
   }

   @Published var annotationItems: [MapAnnotationModel] = []
   @Published var region = MKCoordinateRegion()

   @Published var route: MKPolyline?
   @Published var followMode = true

   let defaultMapCenterPos = CLLocationCoordinate2D(latitude: Constants.defaultLatitude, longitude: Constants.defaultLongitude)

   var changed = false

   var startOrEndChanged = false

   func setCarPos(_ pos: CLLocationCoordinate2D, carId: String, state: EnumCurrentState, direction: Double,speed: Double) {
      var found = false
      if state == .running || state == .waiting {
         if annotationItems.count > 1 {
            annotationItems.removeAll()
         } else if annotationItems.count == 1 {
            let anno = annotationItems[0]
            if anno.car.id != carId {
               annotationItems.removeAll()
            } else {
               annotationItems[0].coordinate = pos
               if direction > 0 {
                  annotationItems[0].car.direction = direction
               }
               annotationItems[0].car.speed = speed
               found = true
               changed = true
            }
         }
      }

      if !found {
         let ai = MapAnnotationModel(coordinate: pos, car: CarInfo(id: carId))
         annotationItems.append(ai)
      }
   }
}
